//
//  main.cpp
//

#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <fstream>
#include <vector>
#include "Matrix.h"
#include <sys/timeb.h>
#include <sys/time.h>

using namespace std;

void splitString(vector<string>* out, string str, string delimiter);

int main(int argc, const char * argv[])
{
    srand((unsigned int)time(NULL));
    
    const bool useStandardInput = true;
    const bool useTPOutputFormat = true;
    const bool useGraphicsOutputFormat = false;

    vector<string> inputLines;
    if(useStandardInput) {
        string line;
        while(getline(cin, line)) {
            inputLines.push_back(line);
        }
    } else {
        ifstream file;
        file.open("in_0.txt");
        if (file.is_open()) {
            while (!file.eof()) {
                string line;
                getline(file, line);
                inputLines.push_back(line);
            }
        }
    }

    Matrix matrix;
    
    matrix.loadFromInput(inputLines);

    timeval tm1, tm2;
    gettimeofday(&tm1, NULL);
    
    matrix.createGraph();
    
    if(!useTPOutputFormat) {
        matrix.printMap();
        cout << endl;
    }
    
    matrix.findPath();
    
    if (useTPOutputFormat) {
        if (useGraphicsOutputFormat) {
            gettimeofday(&tm2, NULL);
            unsigned long long t = 1000 * (tm2.tv_sec - tm1.tv_sec) + (tm2.tv_usec - tm1.tv_usec) / 1000;
            cout << matrix.getN() * matrix.getN() << " " << t << endl;
        } else {
            matrix.printPath(true);
        }
    } else {
        if(matrix.didFindPath()) {
            matrix.printPath(false);
            cout << endl;
            
            int pathRes = 0;
            pathRes = matrix.checkPathOk();
            cout << "Path 1: ";
            if(pathRes == 0) {
                cout << "ok";
            } else if(pathRes == 1) {
                cout << "k error";
            } else if(pathRes == 2) {
                cout << "jump error";
            } else if(pathRes == 3) {
                cout << "end error";
            }
            cout << endl;
        } else {
            cout << "No hay camino." << endl;
        }
    }
    
    return 0;
}


void splitString(vector<string>* out, string str, string delimiter) {
    unsigned long fromIndex = 0;
    unsigned long delimiterIndex = 0;
    while((delimiterIndex = str.find(delimiter, fromIndex)) != -1) {
        out->push_back(str.substr(fromIndex, delimiterIndex));
        fromIndex = delimiterIndex + delimiter.length();
    }
    out->push_back(str.substr(fromIndex, delimiterIndex));
}